import { useViewportStore } from '@renderer/stores/viewport'
import { storeToRefs } from 'pinia'
import {
  Group,
  MeshBasicMaterial,
  SphereGeometry,
  Vector3,
  Mesh,
  CatmullRomCurve3,
  DoubleSide
} from 'three'
import { useFocusObject } from './useFocusObject'
import { useActiveObject } from '@renderer/stores/activeObject'
import { TunnelGeometry } from '@renderer/utils/TunnelGeometry.js'
import { useAddTools } from './useAddTools'
import emiter from './mitt'

const activeObjectStore = useActiveObject()
const { activeVO } = storeToRefs(activeObjectStore)
const viewportStore = useViewportStore()
const { updateCenterPoint, createdLabel, deleteLabel } = useAddTools()
const { publicGroup, transformControls } = storeToRefs(viewportStore)
const { hasGroup } = useAddTools()
export default function useEditor() {
  function createdRoadwayEdit(path: Vector3[]) {
    const group = hasGroup('editor')
    if (activeVO.value) {
      activeVO.value._isEditor = true
      activeVO.value.material.transparent = true
      activeVO.value.material.opacity = 0.1
    }
    const points = createdPoints(path)
    if (group && publicGroup.value) {
      group.add(points)
      publicGroup.value.add(group)
    }
    // focusObject(activeVO.value)
  }

  function closeEditor() {
    const group = hasGroup('editor')
    if (activeVO.value && group) {
      activeVO.value._isEditor = false
      activeVO.value.material.opacity = 1
      group.children.forEach((item) => {
        if (item.name === activeVO.value.name) {
          group.remove(item)
        }
      })
      const css2DRendererDiv = document.getElementsByClassName('css2DRenderer')[0]
      for (let i = css2DRendererDiv.children.length - 1; i >= 0; i--) {
        if (css2DRendererDiv.children[i].getAttribute('name') === activeVO.value.name) {
          css2DRendererDiv.removeChild(css2DRendererDiv.children[i])
        }
      }
    }
  }
  // 节点移动
  transformControls.value?.addEventListener('objectChange', function () {
    const oName = activeVO.value?.parent?.name
    const roadwayGroup = publicGroup.value?.children.find((node) => node.name === '巷道')
    const oNode = roadwayGroup?.children.find((node) => node.name === oName)
    const vecs = activeVO.value?.parent?.children.map((item) => item.position)
    const geometry = createdTunnelGeometryGeometry(vecs, false)
    if (oNode) {
      oNode.geometry = geometry
      oNode.position.set(0, 0, 0)
      updateCenterPoint(oNode)
    }
  })
  // 删除某个节点
  emiter.on('deleteObject', (node) => {
    if (node.name.includes('editor-point')) {
      const oName = node?.parent?.name
      const roadwayGroup = publicGroup.value?.children.find((node) => node.name === '巷道')
      const oNode = roadwayGroup?.children.find((node) => node.name === oName)
      console.log(oNode)
      const vecs = activeVO.value?.parent?.children.map((item) => item.position)
      const index = node.name.replace('editor-point-', '')
      vecs?.splice(index - 1, 1)
      const geometry = createdTunnelGeometryGeometry(vecs)
      if (oNode) {
        oNode.geometry = geometry
        oNode.position.set(0, 0, 0)
        updateCenterPoint(oNode)
      }
      deleteLabel(index)
    }
  })

  function createRoadway(name: string, path: Vector3[], closed: boolean) {
    const roadwayGroup = publicGroup.value?.children.find((node) => node.name === '巷道')
    const oNode = roadwayGroup?.children.find((node) => node.name === name)
    const geometry = createdTunnelGeometryGeometry(path, closed)
    if (oNode) {
      oNode.geometry = geometry
      oNode.position.set(0, 0, 0)
      updateCenterPoint(oNode)
    } else {
      const material = new MeshBasicMaterial({
        color: 0x4fa6df,
        side: DoubleSide,
        transparent: true,
        opacity: 1
      })
      const roadway = new Mesh(geometry, material)
      roadway.name = name
      roadway.userData.type = 'roadway'
      roadwayGroup?.add(roadway)
    }
  }

  return { createdRoadwayEdit, closeEditor, createRoadway }
}

function createdTunnelGeometryGeometry(vecs: Vector3[], closed: boolean) {
  const path = new CatmullRomCurve3(vecs)
  const geometry = new TunnelGeometry(path, TunnelGeometry.pathToUMapping(path, 3, 0.3), closed)
  return geometry
}

function createdPoints(path: Vector3[]) {
  const points = new Group()
  points.name = activeVO.value.name
  const material = new MeshBasicMaterial({ color: 0x00ffff, transparent: true, opacity: 0.5 })
  path.forEach((vec, index) => {
    const geometryPoints = new SphereGeometry(8, 16, 16)
    const point = new Mesh(geometryPoints, material)
    point.name = `editor-point-${index + 1}`
    point.position.copy(vec)
    const label = createdLabel(index + 1, activeVO.value.name)
    point.add(label)
    points.add(point)
  })
  return points
}
